from datetime import datetime

from flask import request, jsonify

from iHome import constants, redis_store
from iHome.api_1_0 import api
from iHome.models import House, Area

"""房屋搜索"""
"""
/houses/   get
请求参数  params
返回响应： 
data={
        'total_page': total_page,
        'houses': house_list
}
"""
@api.route('/houses/')
def search_house():
    params = request.args

    area_id = params.get('aid')
    start_date = params.get('sd')
    end_date = params.get('ed')

    sort_key = params.get('sk')
    page = params.get('p', 1)

    """判空"""
    if not all([area_id, start_date, end_date]):
        return jsonify(errno='4001', errmsg='参数不能为空')

    # """获取房屋的查询集"""
    # house_query = House.query
    """校验区域id是否存在"""
    try:
        Area.query.get(area_id)
    except Exception as e:
        return jsonify(errno='4001', errmsg='地区id不存在')

    """判断日期"""
    start_date = datetime.strptime(start_date, '%Y-%m-%d')
    end_date = datetime.strptime(end_date, '%Y-%m-%d')

    """预定时间开始时间需要小于结束"""
    if start_date >= end_date:
        return jsonify(errno='4001', errmsg='不能预定半天')

    if sort_key == 'booking':
        house_query = House.query.filter(House.area_id == area_id).order_by(House.order_count.desc())

    elif sort_key == 'price_inc':
        """价格从低到高"""
        house_query = House.query.filter(House.area_id == area_id).order_by(House.price.asc())

    elif sort_key == 'price_des':
        """价格从高到低"""
        house_query = House.query.filter(House.area_id == area_id).order_by(House.price.desc())

    else:
        """默认创建时间排序"""
        house_query = House.query.filter(House.area_id == area_id).order_by(House.create_time.desc())

    # print('---------\n' + house_query)

    """使用paginate()"""
    house_paginate = house_query.paginate(int(page), 2, False)

    """获取每页的房屋数据"""
    house = house_paginate.items

    """计算总页数"""
    total_page = house_paginate.pages

    house_list = []
    for i in house:
        house_list.append(i.to_basic_dict())

    """获取缓存中的数据"""
    search_key = 'search_%s_%s_%s_%s_%s' % (area_id, start_date, end_date, sort_key, page)

    try:
        search_data = redis_store.hgetall(search_key)
    except Exception as e:
        return jsonify(errno='4001', errmsg='获取失败')

    # if search_data:
    #     return jsonify(errno='0', errmsg='OK', data={
    #         'total_page': total_page,
    #         'houses': eval(search_data)
    #     })

    search_data = redis_store.hset(search_key, page, str(house_list))

    return jsonify(errno='0', errmsg='OK', data={
        'total_page': total_page,
        'houses': house_list
    })
